//app.js
var common = require('/utils/common.js');
const mtjwxsdk = require("./utils/mtj-wx-sdk.js");
var thisshareTicket = ''
var scenep
function getUrlParam(scene, name) {
  console.log(scene)
  console.log(name)
  var pattern = new RegExp(name + "\=([^&]+)", "g");
  var matcher = pattern.exec(scene);
  console.log(pattern)
  console.log(matcher)
  var items = null;
  if (null != matcher) {
    try {
      items = decodeURIComponent(decodeURIComponent(matcher[1]));
    } catch (e) {
      try {
        items = decodeURIComponent(matcher[1]);
      } catch (e) {
        items = matcher[1];
      }
    }
  }
  return items;
} 
App({
  onLaunch: function (ops) {
    // console.log(this.globalData.userInfo.hasShop)
    const that = this
    wx.getSystemInfo({
      success: res => {
        console.log(res)
        let modelmes = res.model;
        that.globalData.statusBarHeight = res.statusBarHeight
        that.globalData.windowHeight = res.windowHeight
        that.globalData.screenHeight = res.screenHeight
        that.globalData.pixelRatio = res.pixelRatio
        that.globalData.windowWidth = res.windowWidth
        if (modelmes.search('iPhone') != -1) {
          that.globalData.isIphone = true
        }else{
          that.globalData.isAndroid = true
        }
      }
    })
    console.log(this.globalData)
    console.log(ops)
    var pathOption = ''
    console.log(ops.query.length)
    for (var key in ops.query) {
      console.log(key)
      if (pathOption == '') {
        pathOption = key + '=' + ops.query[key]
      } else {
        pathOption = pathOption + '&' + key + '=' + ops.query[key]
      }
      console.log(pathOption)
    }
    if (pathOption == ''){
      this.globalData.path = '/' + ops.path
    }else{
      this.globalData.path = '/' + ops.path + '?' + pathOption
    }
    console.log(this.globalData.path)
    this.globalData.scene = ops.scene
    console.log('ops.scene', this.globalData.scene)
    console.log(this.globalData.scene)
    var f
    if(ops.query.scene){
      var scene = decodeURIComponent(ops.query.scene)
      scenep = decodeURIComponent(ops.query.scene)
      if (getUrlParam(scene, "f") == 't'){
        f = true
      }
      console.log(scene)
      this.globalData.transferuserId = getUrlParam(scene, "userId") || getUrlParam(scene, "userid") || getUrlParam(scene, "ui");
      this.globalData.transferskuId = getUrlParam(scene, "skuid") || getUrlParam(scene, "si");
      this.globalData.fromactive = f
      this.globalData.freeid = getUrlParam(scene, "fr");
      this.globalData.channel = getUrlParam(scene, "channel");
      this.globalData.appid = getUrlParam(scene, "appid");
      this.globalData.skuid = getUrlParam(scene, "skuid") || getUrlParam(scene, "si");
      this.globalData.mark = getUrlParam(scene, "mark");
      this.globalData.freeidactive = getUrlParam(scene, "freeid");
      console.log('scene')
      console.log('scene:' + scene)
      console.log('skuid:' + getUrlParam(scene, "skuid") + getUrlParam(scene, "si"))
      console.log('skuid:' + this.globalData.transferskuId)
      console.log(this.globalData.channel)
    }else{
      if (ops.query.f == 't') {
        f = true
      }
      this.globalData.transferuserId = ops.query.userId || ops.query.userid || ops.query.ui
      this.globalData.transferskuId = ops.query.sku || ops.query.si
      this.globalData.fromactive = f
      this.globalData.freeid = ops.query.fr
      this.globalData.channel = ops.query.channel
      this.globalData.appid = ops.query.appid
      this.globalData.skuid = ops.query.skuid
      this.globalData.mark = ops.query.mark
      this.globalData.freeidactive = ops.query.freeid
      console.log(ops.query.channel)
      console.log(this.globalData.transferskuId)
      console.log(this.globalData)
      console.log(this.globalData.fromactive)
      console.log("appid:" + this.globalData.appid)
      console.log("skuid:" + this.globalData.skuid)
      console.log("mark:" + this.globalData.mark)
    }
    console.log('freeid:',this.globalData.freeid)
    console.log('skuid:', this.globalData.transferskuId)
    console.log('userid:', this.globalData.transferuserId)
    console.log('freeidactive:' + this.globalData.freeidactive)
    thisshareTicket = ops.shareTicket
    this.globalData.thisshareTicket = thisshareTicket
    this.globalData.shareTicket = ops.shareTicket
    // 展示本地存储能力
    // var logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)
    // wx.getStorage({
    //   key: 'time',
    //   success: function (res) {
    //     console.log(res.data)
    //     var nowtime = new Date().getTime()
    //     var time = (nowtime - res.data) / 1000 / 60 / 60;
    //     console.log(time)
    //     if (time > 72){
    //       wx.clearStorage()
    //     }else{
    //       wx.setStorage({
    //         key: "time",
    //         data: nowtime
    //       })
    //     }
    //   },
    //   fail: function (){
    //     console.log('失败')
    //     wx.setStorage({
    //       key: "time",
    //       data: new Date().getTime()
    //     })
    //   }
    // })
    if (wx.getStorageSync('jsessionId')){
      this.globalData.jsessionId = wx.getStorageSync('jsessionId')
    }
    if (wx.getStorageSync('spreader')){
      this.globalData.spreader = wx.getStorageSync('spreader')
    }
    if (wx.getStorageSync('sharelink')) {
      this.globalData.sharelink = wx.getStorageSync('sharelink')
    }
    if (wx.getStorageSync('sessionId')) {
      this.globalData.sessionId = wx.getStorageSync('sessionId')
    }
    if (wx.getStorageSync('userInfo')) {
      this.globalData.userInfo = wx.getStorageSync('userInfo')
    }
    if (wx.getStorageSync('userId')) {
      this.globalData.userId = wx.getStorageSync('userId')
    }
    console.log(wx.getStorageSync('sessionId'), this.globalData.sessionId)
    console.log(wx.getStorageSync('userInfo'), this.globalData.userInfo)
  },
  onShow: function (ops) {
    var f
    console.log(this.globalData)
    console.log("onshow")
    console.log('ops:',ops)
    // this.globalData.freeidactive = ''
    // this.globalData.freeid = ''
    // this.globalData.skuid = ''
    // this.globalData.item = ''
    console.log('item')
    console.log(this.globalData.item)
    if (ops.query.center){
      this.globalData.center = true
    }
    if (ops.query.scene) {
      if (getUrlParam(scene, "f") == 't') {
        f = true
      }
      var scene = decodeURIComponent(ops.query.scene)
      this.globalData.transferuserId = getUrlParam(scene, "userid") || getUrlParam(scene, "userId") || getUrlParam(scene, "ui");
      this.globalData.transferskuId = getUrlParam(scene, "skuid") || getUrlParam(scene, "si");
      this.globalData.fromactive = f;
      this.globalData.freeid = getUrlParam(scene, "fr");
      this.globalData.channel = getUrlParam(scene, "channel");
      this.globalData.appid = getUrlParam(scene, "appid");
      this.globalData.skuid = getUrlParam(scene, "skuid");
      this.globalData.mark = getUrlParam(scene, "mark");
      this.globalData.freeidactive = getUrlParam(scene, "freeid");
      console.log(this.globalData.transferuserId, this.globalData.transferskuId)
    } else {
      if (ops.query.f == 't') {
        f = true
      }
      this.globalData.transferuserId = ops.query.userId || ops.query.userid || ops.query.ui
      this.globalData.transferskuId = ops.query.sku || ops.query.si
      this.globalData.fromactive = f
      this.globalData.freeid = ops.query.fr
      this.globalData.channel = ops.query.channel
      this.globalData.appid = ops.query.appid
      this.globalData.skuid = ops.query.skuid
      this.globalData.mark = ops.query.mark
      this.globalData.freeidactive = ops.query.freeid
    }
    console.log('ops:',ops)
    console.log('freeidactive:',this.globalData.freeidactive)
    console.log(this.globalData)
    console.log(this.globalData.fromactive)
    let that = this;
    console.log('判断sku' + this.globalData.transferskuId)
    wx.getSystemInfo({
      success: res => {
        console.log('iphone')
        console.log(res)
        var iphonexs = false
        if (res.screenHeight == 812 && res.screenWidth == 375) {
          iphonexs = true
        }
        if (res.screenHeight == 836 && res.screenWidth == 412) {
          iphonexs = true
        }
        let modelmes = res.model;
        that.globalData.statusBarHeight = res.statusBarHeight
        that.globalData.windowHeight = res.windowHeight
        if (modelmes.search('iPhone X') != -1 || iphonexs || modelmes.search('iPhone 11') != -1) {
          that.globalData.isIphoneX = true
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    // url: 'https://miniapp.meyoutao.com',
    url: 'http://26031mg941.qicp.vip:14293',
    seachkey: '',
    seachrecord: [],
    seachid: '',
    clipboard: '',
    isIphone: false,
    isAndroid: false,
    getUserInfo: false,
    newnotice:false,
    newuser: false,
    fromShopkeeper: false,
    selected: 0,
    tabtop: '',
    utop: ''
  },
  async login(thisshareTicket) {
    wx.showLoading({
      title: '登录中',
    })
    console.log(this.globalData)
    this.globalData.sessionId = ''
    const that = this
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log(res.code)
        if (thisshareTicket) {
          wx.getShareInfo({
            shareTicket: thisshareTicket,
            complete: res => {
              console.log(res)
              console.log('shareTicket' + thisshareTicket)
              getApp().globalData.shareEncryptedData = res.encryptedData
              getApp().globalData.shareIv = res.iv
              console.log('shareEncryptedData' + getApp().globalData.shareEncryptedData)
              console.log('shareIv' + getApp().globalData.shareIv)
            }
          })
        }
        console.log('传入scene' + getApp().globalData.scene)
        common.post({
          url: '/wxa/user/login', data: { code: res.code, channelCode: getApp().globalData.channel || '', scene: getApp().globalData.scene || '' }
        })
          .then((json) => {
            console.log(json)
            //json.data.user = null
            const pages = getCurrentPages()
            const currentPage = pages[pages.length - 1]
            const url = currentPage.route
            const options = currentPage.options
            let urlWithArgs = `/${url}?`
            for (let key in options) {
              const value = options[key]
              urlWithArgs += `${key}=${value}&`
            }
            urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
            getApp().globalData.thispath = urlWithArgs
             if (json.data.user == null) {
              getApp().globalData.jsessionId = json.data.data.sessionId
              wx.setStorage({
                key: "jsessionId",
                data: json.data.data.sessionId
              })
              console.log(1)
              console.log(getApp().globalData.fromactive)
              wx.redirectTo({
                url: '/pages/authorized/authorized',
                success(res) {
                  console.log(res)
                },
                fail(res) {
                  console.log(res)
                }
              })
            } else {
              console.log(2)
              console.log(getApp().globalData)
              console.log(getApp().globalData.fromactive)
              getApp().globalData.spreader = json.data.user.isSpreader
              getApp().globalData.sharelink = json.data.user.inviteLink
              getApp().globalData.sessionId = json.data.user.sessionId
              getApp().globalData.userInfo = json.data.user
              getApp().globalData.userId = json.data.user.userId
              wx.setStorage({
                key: "spreader",
                data: json.data.user.isSpreader
              })
              wx.setStorage({
                key: "sharelink",
                data: json.data.user.inviteLink
              })
              wx.setStorage({
                key: "sessionId",
                data: json.data.user.sessionId
              })
              wx.setStorage({
                key: "userId",
                data: json.data.user.userId
              })
              wx.setStorage({
                key: "userInfo",
                data: json.data.user
              })
              console.log(getApp().globalData.userId, getApp().globalData.sessionId)
              console.log(getApp().globalData.fromactive, getApp().globalData.isdetail)
              console.log('freeidactive:' + getApp().globalData.freeidactive)

              if (getApp().globalData.freeidactive) {
                getApp().globalData.freeid = getApp().globalData.freeidactive
                getApp().globalData.freeidactive = ''
                console.log('freeid:' + getApp().globalData.freeid)
                wx.redirectTo({
                  url: '/pages/activeitemdetail/activeitemdetail?fromshare=true'
                })
              } else if (getApp().globalData.fromactive) {
                console.log('freeid:' + getApp().globalData.freeid)
                console.log(getApp().globalData.path)
                wx.redirectTo({
                  url: getApp().globalData.path
                })
              } else if (getApp().globalData.isdetail && !getApp().globalData.item.is99) {
                wx.redirectTo({
                  url: '/pages/itemdetail/itemdetail?fromshare=true'
                })
              } else if (getApp().globalData.center) {
                wx.redirectTo({
                  url: '/pages/usercenter/usercenter'
                })
              } else {
                console.log('刷新')
                wx.hideLoading()
                wx.showToast({
                  title: '登录成功',
                  icon: 'none',
                  duration: 2000
                })
                const pages = getCurrentPages()
                //声明一个pages使用getCurrentPages方法
                const perpage = pages[pages.length - 1]
                //声明一个当前页面
                console.log(perpage)
                perpage.onLoad()
                //执行刷新
              }

            }

          })
        
      },
      fail(res){
        console.log('获取用户登录态失败！' + res)
        getApp().timeOutTip()
      }
    })
  },
  timeOutTip(){
    const that = this
    wx.showModal({
      title: '连接超时',
      content: '请检查网络连接',
      showCancel: false,
      success(res) {
        if (res.confirm) {
          wx.reLaunch({
            url: getApp().globalData.path
          })
        }
      }
    })
  }
})